/**
 * 这是服务器端的控制界面，可以启动服务器，关闭服务器
 * 可以管理用户
 */
package com.dq.view;


import com.dq.common.Message;
import com.dq.common.MessageType;
import com.dq.model.MyQqServer;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class MyServerFrame extends JFrame implements ActionListener,Runnable{

	JPanel mainPanel;
	JButton startServerButton,stopServerButton;
	MyQqServer qqServer;
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyServerFrame qsf = new MyServerFrame();
	}
	public MyServerFrame(){
		//创建服务器
		qqServer = new MyQqServer();
		//初始化界面
		init();
	}
	public void init(){
		mainPanel = new JPanel();
		startServerButton = new JButton("启动服务器");
		startServerButton.addActionListener(this);
		stopServerButton = new JButton("关闭服务器");
		stopServerButton.addActionListener(this);
		mainPanel.add(startServerButton);
		mainPanel.add(stopServerButton);

		this.add(mainPanel);
		this.setSize(500,400);
//		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.setVisible(true);
		addWindowListener(new closeWindow(this));
	}
	//事件监听器
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		//开启服务器
		if(e.getSource()==startServerButton) {

			if(!qqServer.isClose()) {
				Thread t = new Thread(this);
				t.start();
			}
		}else if(e.getSource()==stopServerButton) {
			this.closeServer();
		}
	}
	class closeWindow extends WindowAdapter{

		MyServerFrame my;
		public closeWindow(MyServerFrame my) {
			super();
			// TODO Auto-generated constructor stub
			this.my = my;
		}


		public void windowClosing(WindowEvent e) {

			my.closeServer();
			System.exit(0);
		}

	}
	public void closeServer() {

		if(qqServer.isClose()) {
			Message mm = new Message();
			mm.setMesType(MessageType.message_server_close);
			try {
				Socket s = new Socket("localhost",9999);
				ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
				oos.writeObject(mm);
				qqServer.setFlag(false);
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	@Override
	//用于开启服务器
	public void run() {
		// TODO Auto-generated method stub
		qqServer.openServer();
	}

}
